#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
DEV_VISION 系统全面检查脚本
快速验证系统各模块基础状态
"""

from standard_imports_template import *
import requests
import time

def check_environment():
    """检查基础环境"""
    print("🔍 检查基础环境...")
    
    try:
        # 检查应用启动
        app = create_app()
        print("✅ Flask应用启动正常")
        
        # 检查配置管理
        from backend.config.config_manager import ConfigManager
        cm = ConfigManager()
        print("✅ 配置管理器正常")
        
        # 检查数据库连接
        with get_app_context():
            db.session.execute('SELECT 1')
            print("✅ 数据库连接正常")
            
        return True
    except Exception as e:
        print(f"❌ 环境检查失败: {e}")
        return False

def check_database_data():
    """检查数据库数据状态"""
    print("\n📊 检查数据库数据...")
    
    try:
        with get_app_context():
            user_count = User.query.count()
            student_count = Student.query.count()
            vision_count = VisionRecord.query.count()
            intervention_count = InterventionRecord.query.count()
            permission_count = Permission.query.count()
            role_count = Role.query.count()
            
            print(f"👥 用户数: {user_count}")
            print(f"🎓 学生数: {student_count}")
            print(f"👁️ 视力记录数: {vision_count}")
            print(f"🏥 干预记录数: {intervention_count}")
            print(f"🔑 权限数: {permission_count}")
            print(f"👑 角色数: {role_count}")
            
            # 检查核心数据完整性
            if permission_count >= 90:
                print("✅ 权限系统数据完整")
            else:
                print(f"⚠️ 权限数据可能不完整 (期望>=90, 实际{permission_count})")
                
            if user_count > 0 and student_count > 0:
                print("✅ 基础测试数据存在")
            else:
                print("⚠️ 缺少基础测试数据")
                
        return True
    except Exception as e:
        print(f"❌ 数据检查失败: {e}")
        return False

def check_api_endpoints():
    """检查核心API端点"""
    print("\n🌐 检查核心API端点...")
    
    # 假设服务运行在5000端口
    base_url = "http://localhost:5000"
    
    endpoints = [
        ("/api/dashboard/overview?page=welcome", "仪表板API"),
        ("/api/config/user_profile_editable_fields", "配置API"),
        ("/api/auth/check", "认证检查API"),
    ]
    
    success_count = 0
    total_count = len(endpoints)
    
    for endpoint, name in endpoints:
        try:
            response = requests.get(f"{base_url}{endpoint}", timeout=5)
            if response.status_code in [200, 401]:  # 200成功或401需要认证都是正常的
                print(f"✅ {name}: {response.status_code}")
                success_count += 1
            else:
                print(f"⚠️ {name}: {response.status_code}")
        except requests.exceptions.ConnectionError:
            print(f"❌ {name}: 连接失败 (服务可能未启动)")
        except Exception as e:
            print(f"❌ {name}: {e}")
    
    if success_count == total_count:
        print("✅ 所有核心API端点响应正常")
        return True
    else:
        print(f"⚠️ {success_count}/{total_count} API端点正常")
        return False

def check_module_files():
    """检查核心模块文件存在性"""
    print("\n📁 检查核心模块文件...")
    
    core_modules = [
        "backend/api/query_api.py",
        "backend/api/student_complete_api.py", 
        "backend/api/vision_api.py",
        "backend/api/intervention_api.py",
        "backend/api/followup_api.py",
        "backend/api/import_api.py",
        "backend/api/analysis_api.py",
        "backend/api/chart_api.py",
        "backend/api/auth_api.py",
        "backend/api/user_api.py",
        "backend/api/config_api.py",
        "backend/api/dashboard_api.py",
        "backend/config/config_manager.py",
        "backend/config/constants_v2.py",
    ]
    
    missing_files = []
    for module in core_modules:
        if not os.path.exists(module):
            missing_files.append(module)
        else:
            print(f"✅ {module}")
    
    if missing_files:
        print(f"\n❌ 缺少以下核心文件:")
        for file in missing_files:
            print(f"   - {file}")
        return False
    else:
        print("✅ 所有核心模块文件存在")
        return True

def check_miniprogram_files():
    """检查微信小程序模块文件"""
    print("\n📱 检查微信小程序模块文件...")
    
    mp_modules = [
        "backend/api/miniprogram/auth_api.py",
        "backend/api/miniprogram/query_api.py",
        "backend/api/miniprogram/intervention_api.py",
        "backend/api/miniprogram/communication_api.py",
        "backend/api/miniprogram/social_api.py",
        "miniprogram/app.js",
        "miniprogram/app.json",
    ]
    
    missing_files = []
    for module in mp_modules:
        if not os.path.exists(module):
            missing_files.append(module)
        else:
            print(f"✅ {module}")
    
    if missing_files:
        print(f"\n❌ 缺少以下小程序文件:")
        for file in missing_files:
            print(f"   - {file}")
        return False
    else:
        print("✅ 所有小程序模块文件存在")
        return True

def generate_test_report():
    """生成测试报告"""
    print("\n📋 生成系统状态报告...")
    
    checks = [
        ("环境检查", check_environment()),
        ("数据库数据", check_database_data()),
        ("核心模块文件", check_module_files()),
        ("小程序模块文件", check_miniprogram_files()),
        ("API端点检查", check_api_endpoints()),
    ]
    
    print("\n" + "="*50)
    print("🎯 系统状态总结")
    print("="*50)
    
    passed = 0
    total = len(checks)
    
    for check_name, result in checks:
        status = "✅ 通过" if result else "❌ 失败"
        print(f"{check_name}: {status}")
        if result:
            passed += 1
    
    print(f"\n总体状态: {passed}/{total} 项检查通过")
    
    if passed == total:
        print("🎉 系统状态良好，可以开始详细功能测试！")
        print("\n📋 下一步建议:")
        print("1. 启动服务: python app_dev.py")
        print("2. 执行自动化测试: pytest tests/ -v")
        print("3. 参考文档: docs/系统全面功能检查与测试方案.md")
    else:
        print("⚠️ 系统存在问题，请先解决基础问题再进行详细测试")
        print("\n🔧 解决建议:")
        print("1. 检查虚拟环境是否正确激活")
        print("2. 验证数据库迁移是否完成")
        print("3. 确认所有依赖包已安装")

def main():
    """主函数"""
    print("🚀 DEV_VISION 系统全面检查")
    print("="*50)
    
    # 执行各项检查
    generate_test_report()

if __name__ == "__main__":
    main()
